package com.imooc.dianping.controller.admin;

import com.imooc.dianping.common.*;
import com.imooc.dianping.model.Seller;
import com.imooc.dianping.request.PageQuery;
import com.imooc.dianping.request.SellerCreateReq;
import com.imooc.dianping.service.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin/seller")
public class AdminSellerController {

    @Autowired
    private SellerService sellerService;

    @RequestMapping("/index")
    @AdminPermission
    public String index(PageQuery pageQuery, Model model) {
        model.addAttribute("CONTROLLER_NAME", "seller");
        model.addAttribute("ACTION_NAME", "index");
        model.addAttribute("data", sellerService.selectAll(pageQuery));
        return "/admin/seller/index";
    }

    @RequestMapping("/createpage")
    @AdminPermission
    public String createPage(Model model) {
        model.addAttribute("CONTROLLER_NAME", "seller");
        model.addAttribute("ACTION_NAME", "create");
        return "/admin/seller/create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @AdminPermission
    public String create(@Valid SellerCreateReq sellerCreateReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, CommonUtil.processErrorString(bindingResult));
        }
        Seller seller = new Seller();
        seller.setName(sellerCreateReq.getName());
        sellerService.create(seller);
        return "redirect:/admin/seller/index";
    }

    @RequestMapping(value="down",method = RequestMethod.POST)
    @AdminPermission
    @ResponseBody
    public CommonRes down(@RequestParam(value="id")Integer id) throws BusinessException {
        Seller sellerModel = sellerService.changeStatus(id,1);
        return CommonRes.create(sellerModel);
    }

    @RequestMapping(value="up",method = RequestMethod.POST)
    @AdminPermission
    @ResponseBody
    public CommonRes up(@RequestParam(value="id")Integer id) throws BusinessException {
        Seller sellerModel = sellerService.changeStatus(id,0);
        return CommonRes.create(sellerModel);
    }
}
